//
//  PlayerManager.m
//  avqueue
//
//  Created by 隗杰 on 16/4/1.
//  Copyright © 2016年 baobao. All rights reserved.
//

#import "PlayerManager.h"
#import "BottomView.h"

@interface PlayerManager ()<BottomViewDelegate>{
    BOOL _played;
    //    NSString *_totalTime;
    NSDateFormatter *_dateFormatter;
}
@property (copy,nonatomic)NSString *totalTime;
@property (nonatomic,assign)NSInteger index;
@property (strong,nonatomic)AVPlayerItem *currentItem;
@property (nonatomic ,strong) id playbackTimeObserver;
@property (strong,nonatomic)NSArray *theItems;
@property (strong,nonatomic)AVQueuePlayer *theQueuePlayer;
@property (strong,nonatomic)BottomView *bottomView;

@end

@implementation PlayerManager

+ (instancetype)sharedPlayerManager {
    static dispatch_once_t onceToken;
    static PlayerManager *manager;
    dispatch_once(&onceToken, ^{
        manager = [[PlayerManager alloc] init];
    });
    return manager;
}
// 接口方法
- (void)PlayWithUrlStrArr:(NSArray *)urlStrArr {
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSString *urlStr in urlStrArr) {
        NSURL *url = [NSURL URLWithString:urlStr];
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
        [arrM addObject:item];
    }
    self.theItems = arrM;
    self.theQueuePlayer = [AVQueuePlayer queuePlayerWithItems:self.theItems];
    [self.theQueuePlayer play];
    [self observe];
}
- (void)playAtIndex:(NSInteger)index
{
    [self.theQueuePlayer removeAllItems];
    for (int i = (int)index; i < self.theItems.count; i ++) {
        AVPlayerItem* obj = [self.theItems objectAtIndex:i];
        if ([self.theQueuePlayer canInsertItem:obj afterItem:nil]) {
            [obj seekToTime:kCMTimeZero];
            [self.theQueuePlayer insertItem:obj afterItem:nil];
        }
    }
}
// KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            CMTime duration = self.theQueuePlayer.currentItem.duration;// 获取视频总长度
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            self.totalTime = [self convertTime:totalSecond];// 转换成播放时间
            //            self.durationBlock(duration);
            [BottomView sharedBottomView].duration = duration;
            NSLog(@"movie total duration:%f",CMTimeGetSeconds(duration));
            [self monitoringPlayback:self.theQueuePlayer.currentItem];// 监听播放状态
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = self.theQueuePlayer.currentItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        
        CGFloat progress = timeInterval / totalDuration;
        [BottomView sharedBottomView].progress = progress;
        [BottomView sharedBottomView].delegate = self;
    }
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.theQueuePlayer currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    __weak typeof(self) weakSelf = self;
    weakSelf.playbackTimeObserver = [weakSelf.theQueuePlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        if (playerItem == weakSelf.theItems[weakSelf.index]) {
            CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
            
                CGFloat totalSecond = self.self.theQueuePlayer.currentItem.duration.value / self.theQueuePlayer.currentItem.duration.timescale;// 转换成秒
                self.totalTime = [self convertTime:totalSecond];
            
            
            [BottomView sharedBottomView].currentSecond = currentSecond;
            NSString *timeString = [weakSelf convertTime:currentSecond];
            if ([timeString isEqualToString:self.totalTime]) {
                [self bottomViewDidClickNextAudioBtn:nil];
            }
            //            weakSelf.timeLabel.text
            NSString *timeText = [NSString stringWithFormat:@"%@/%@",timeString,weakSelf.totalTime];
            [BottomView sharedBottomView].timeText = timeText;
        }
    }];
}
#pragma mark - view的代理方法
- (void)bottomViewDidPlayOrStop:(BottomView *)bottom butnSelected:(BOOL)selected {
    if (selected) {
        [self.theQueuePlayer pause];
        
    } else {
        [self.theQueuePlayer play];
    }
}
- (void)bottomViewSliderViewDidChangeValue:(BottomView *)bottomView senderValue:(float)value {
    CMTime changedTime = CMTimeMakeWithSeconds(value, 1);
    __weak typeof(self) weakSelf = self;
    [self.theQueuePlayer seekToTime:changedTime completionHandler:^(BOOL finished) {
        [weakSelf.theQueuePlayer play];
    }];
    
}
- (void)bottomViewDidClickLastAudioBtn:(BottomView *)bottomView {
    if (self.index == 0) {
//        ++self.index ;
        return;
//        [self playAtIndex:--self.index];
    } else{
        [self playAtIndex:--self.index];
        [self removeNextObserve];
        [self observe];
    }
}

- (void)bottomViewDidClickNextAudioBtn:(BottomView *)bottomView {
    self.index ++;
    if (self.index == self.theItems.count) {
        --self.index ;
        return;
    }
    [self.theQueuePlayer advanceToNextItem];

    [self removeLastObserve];
    [self observe];
}


// 将时间转换为字符串
- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    return showtimeNew;
}
- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}
#pragma mark - 删除通知观察者
- (void)removeNextObserve {
    [self.theItems[self.index + 1] removeObserver:self forKeyPath:@"status" context:nil];
    [self.theItems[self.index + 1] removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];

}
- (void)removeLastObserve {
    [self.theItems[self.index - 1] removeObserver:self forKeyPath:@"status" context:nil];
    [self.theItems[self.index - 1] removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];

}
#pragma mark - 注册通知与观察者
- (void)observe {
    [self.theQueuePlayer.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self.theQueuePlayer.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)dealloc {
    [self.theQueuePlayer.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.theQueuePlayer.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [self.theQueuePlayer removeTimeObserver:self.playbackTimeObserver];
    
    NSLog(@"88");
}
@end
